var startRoad4Select = "",
    endRoad4Select = "",
    currentActorId = 3,
    signalMachineFlag = 0,
    signalMachineProvince = 0,
    signalMachineCity = 0,
    signalMachineArea = 0,
    orgDataFlag = 0;
    alarmBinding = 0;
    localOrgId = 0;
if (gUserLoginResult.userActors.indexOf("7") >= 0) currentActorId = 7;
if (gUserLoginResult.userActors.indexOf("1") >= 0) currentActorId = 1;
var myDate = new Date(),
    date = myDate.getFullYear() + "-" +
        myDateFormat(myDate.getMonth() + 1) + "-" +
        myDateFormat(myDate.getDate());

function myDateFormat(s) {
    return s < 10 ? '0' + s : s;
}

var localActorId;
$(function () {
    localActorId = currentActorId;
    localOrgId = gUserLoginResult.orgId;
    gMainDT = $("#mainDataTable").DataTable({
        ajax: {
            url: "../rds_signalMachineManage/getSignalMachine4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#mainDataTable').DataTable().search(this.value);
                d.actorIds = localActorId;
                d.orgId = localOrgId;
                d.audit = false;
                d.startRoad = startRoad4Select;
                d.endRoad = endRoad4Select;
                d.alarmBinding = alarmBinding;
            }
        },
        columns: [{
            data: "signalMachineId",
            render: function (data, type, row, meta) {
                var checkId = "checkbox" + (parseInt(meta.row) + 1);
                return "<input type='checkbox' value='" + data + "' id='" + checkId + "'>";
            }
        }, {
            data: "signalMachineId",
            render: function (data, type, row) {
                var isAlarm = row.alarmDeviceId;
                var state=row.deviceState;
                var html = data;
                if (isAlarm)
                    html += "<i class='fa fa-bell' style='color: "+gColor[state]+";' title='"+gDeviceState[state]+"'></i>";
                return html;
            }
        }, {
            data: "signalMachinePhoto",
            render: function (data, type, row) {
                return "<img src='" + data + "' style='width: 50px; height: 40px; cursor: pointer' " +
                    "onclick='$.showPicModal(\"" + data + "\")'>";
            }
        }, {
            data: null,
            render: function (data, type, row) {
                var str = "<button id='showMap' " +
                    "onclick='$.showMap(" + row.signalMachineLongitude + "," + row.signalMachineLatitude + ")' " +
                    "class='btn  btn-primary  btn-xs btn-flat' title='地图位置'>" +
                    "<i class='glyphicon glyphicon-map-marker'></i></button> ";
                str += row.signalMachineProvince + " " + row.signalMachineCity + " " + row.signalMachineArea;
                return str;
            }
        }, {
            data: null,
            render: function (data, type, row) {
                return row.signalMachineStartRoad + "——" + row.signalMachineEndRoad;
            }
        }, {
            data: "signalMachineOrgName"
        }, {
            data: "signalMachineCreatorName"
        }, {
            data: "signalMachineInstallTime"
        }, {
            data: "signalMachineId",
            render: function (data, type, row) {
                var html = "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showInfo(" + JSON.stringify(row) + ")' title='信息查看'>" +
                    "<i class='glyphicon glyphicon-eye-open'></i></button> " +
                    "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showQrcode(" + JSON.stringify(row) + ")' title='二维码'>" +
                    "<i class='glyphicon glyphicon-qrcode'></i></button>";
                if (row.alarmDeviceId)
                    html += " <button class='btn btn-primary btn-xs btn-flat' " +
                        "onclick='$.showAlarmHistory(\"" + row.alarmDeviceId + "\")' title='报警历史'>" +
                        "<i class='glyphicon glyphicon-th-list'></i></button>";
                return html;
            }
        }, {
            data: "signalMachineId",
            render: function (data, type, row) {
                var buttonOperation = "";
                if (row.signalMachineIsComplete == 1)
                    buttonOperation += "<button  class='btn  btn-success btn-xs btn-flat' title='已审核'>" +
                        "<i class='fa  fa-check-square-o'></i></button> ";
                else
                    buttonOperation += "<button  class='btn  btn-danger btn-xs btn-flat' title='未审核'>" +
                        "<i class='fa fa-square-o'></i></button> ";

                var buttonUpdate = "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showUpdateSignalMachine(" + JSON.stringify(row) + ")' title='编辑'>" +
                    "<i class='fa fa-edit'></i></button> ";
                gUpdate == 0 ? buttonOperation : buttonOperation += buttonUpdate;

                var buttonBinging = "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.boundAlarm(" + data + ")' title='绑定设备'>" +
                    "<i class='fa fa-gear '></i></button> ";
                gUpdate == 0 ? buttonOperation : buttonOperation += buttonBinging;

                var buttonDelete = "<button class='btn btn-primary btn-xs btn-flat' " +
                    "onclick='$.showDeleteSignalMachine(" + data + ")' title='删除'>" +
                    "<i class='fa fa-minus-square'></i></button>";
                gDelete == 0 ? buttonOperation : buttonOperation += buttonDelete;

                return buttonOperation == "" ? buttonOperation = "无权限" : buttonOperation;
            }
        }],
        dom: "<'row'<'col-md-2'l><'#mainToolbar.col-md-10'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            // 下拉工具栏按钮的权限
            $("#mainToolbar").empty();
            var strToolBar = "<div class='pull-right'><div class='btn-group'>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat'><i class='fa fa-cog'></i> 操作</button>" +
                "<button type='button' class='btn btn-primary btn-sm btn-flat dropdown-toggle' " +
                "data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'>" +
                "<span class='caret'></span><span class='sr-only'>切换下拉</span></button>" +
                "<ul class='dropdown-menu'>" +
                "<li>" +
                "<button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='gMainDT.ajax.reload(null, false);'><i class='fa fa-refresh'></i> 刷新</button>" +
                "</li>";

            var buttonAdd = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.showAddSignalMachine()'><i class='fa fa-plus-square'></i> 添加</button></li>";
            gInsert == 0 ? strToolBar : strToolBar += buttonAdd;

            var buttonDelete = "<li><button href='#' class='btn btn-primary btn-sm btn-flat btn-block' " +
                "onclick='$.showDeleteSignalMachine(0)'><i class='fa fa-minus-square'></i> 删除</button></li>";
            gDelete == 0 ? strToolBar : strToolBar += buttonDelete;

            var html2 = "";
            if(currentActorId == 1)
                html2 += "<select id='orgId4Select' style='max-width: 280px' onchange='$.getRoad(1);' class='form-control'>" + gOrgListHtml +"</select>&nbsp;";
            strToolBar += "</ul></div> " +
                "<div class='input-group-sm' style='display:inline-block'>" + html2 +
                "<select onchange='$.getRoad(2);'  style='width: 80px' class='form-control mysize' id='startRoad4Select'>" +
                "<option value=''>起/止</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='endRoad4Select'>" +
                "<option value=''>止/起</option>" +
                "</select>&nbsp;" +
                "<select class='form-control mysize'  style='width: 80px' id='alarm4Select'>" +
                "<option value='0'>报警器</option>" +
                "<option value='1'>已绑定</option>" +
                "<option value='2'>未绑定</option>" +
                "</select>&nbsp;" +
                "<input type='text' class='form-control' style='width: 80px' id='searchText' placeholder='项目编号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$(this).searchDT()'>" +
                "<i class='fa fa-search'></i></button></div></div>";

            $("#mainToolbar").append(strToolBar);
            $.getRoad(1);//初始化选择框
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        displayLength: 20,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
    });

    var oTable = $('#mainDataTable').dataTable();
    if (gUserLoginResult.userActors.indexOf('1') > -1) {
        oTable.fnSetColumnVis(5, false);
        oTable.fnSetColumnVis(7, false);
    } else if (gUserLoginResult.userActors.indexOf('7') > -1) {
        oTable.fnSetColumnVis(0, false);
        oTable.fnSetColumnVis(5, false);
        oTable.fnSetColumnVis(7, false);
        oTable.fnSetColumnVis(9, false);
    } else {
        oTable.fnSetColumnVis(6, false);
    }


});

var gActorId = gUserLoginResult.userActors.includes("1") ? 1 : 2;
$.getOrgList = function () {
    var html = "", result = "";
    $.ajax({
        url: "../rds_fault/getOrg4Select",
        type: "post",
        async: false,
        data: {
            actorId: gActorId,
            orgId: gUserLoginResult.orgId
        },
        success: function (msg) {
            if (msg) {
                if (msg.isSuccess) {
                    var jsonData = msg.jsonData;
                    var orglist = "";
                    if (jsonData.length == 0) {
                        firstOrgId = gUserLoginResult.orgId;
                        result = "<option value='" + gUserLoginResult.orgId + "'>" + gUserLoginResult.orgName + "</option>"
                    }
                    else {

                        for (var i in jsonData) {
                            orglist += "," + jsonData[i].orgId;
                            html += "<option value='" + jsonData[i].orgId + "'>" + jsonData[i].orgName + "</option>"
                        }
                        orglist = orglist.substr(1);
                        if (gActorId == 1) {
                            result += "<option value='-2'>全部</option>" +
                                "<option value='-1'>未设置</option>"
                            firstOrgId = -2;
                        }
                        else {
                            firstOrgId = orglist
                            result += "<option value='" + orglist + "'>全部</option>"
                        }
                        result += html;
                    }

                }

            }
        }
    })
    return result;
}

var gOrgListHtml = $.getOrgList();

/**
 * @Description:
 * @Author: WYX.
 * @Date: 2018/5/1 16:53.
 */
var alarmHistoryDt = null;

$.showAlarmHistory = function (alarmDeviceId) {
    alarmHistoryDt = $("#alarmHistoryDataTable").DataTable({
        ajax: {
            url: "../rds_signalMachineManage/showAlarmHistory",
            type: "POST",
            data: function (d) {
                d.search = $('#alarmHistoryDataTable').DataTable().search(this.value);
                d.deviceId = alarmDeviceId;
                d.deviceType = 3;
            }
        },
        columns: [{
            data: null,
            targets: 0
        }, {
            data: "alarmPushContent"
        }, {
            data: "alarmPushTime",
            render: function (data) {
                return formatDateTime(data)
            }
        }, {
            data: "alarmDeviceId"
        }],
        dom: "<'row'<'#alarmHistoryTool.col-md-12'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            $("#alarmHistoryTool").empty();
            var strToolBar = "<div class='input-group input-group-sm' style='float: left;'>" +
                "<input type='text' class='form-control' id='alarmHistoryDatePicker' placeholder='操作时间' readonly>" +
                "<span class='input-group-btn'>" +
                "<button class='btn btn-primary btn-flat' type='button' " +
                "onclick='$(this).searchAlarmHistory()'><i class='fa fa-search'></i>" +
                "</button></span></div>";
            $("#alarmHistoryTool").append(strToolBar);
            $("#alarmHistoryDatePicker").bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    $(this).searchAlarmHistory();
                }
            });
            $("#alarmHistoryDatePicker").focus(function () {
                $('#alarmHistoryDatePicker').daterangepicker({
                    autoUpdateInput: false,
                    locale: {
                        format: 'YYYY-MM-DD',
                        applyLabel: '确认',
                        cancelLabel: '取消',
                        fromLabel: '从',
                        toLabel: '到',
                        weekLabel: 'W',
                        customRangeLabel: 'Custom Range',
                        daysOfWeek: ["日", "一", "二", "三", "四", "五", "六"],
                        monthNames: ["一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月"],
                    }
                }).on('cancel.daterangepicker', function (ev, picker) {
                    $(this).val('');
                }).on('apply.daterangepicker', function (ev, picker) {
                    $(this).val(picker.startDate.format('YYYY-MM-DD') + ' - ' + picker.endDate.format('YYYY-MM-DD'));
                });
            })
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        destroy: true,
        displayLength: 10,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    $("#alarmHistoryModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
}

$.fn.searchAlarmHistory = function () {
    var search = $("#alarmHistoryDatePicker").val().replace(/'/g, '');
    alarmHistoryDt.search(search).draw();
};

$.getRoad = function (type) {
    var mOrgId = $("#orgId4Select").val();
    var localOrg = gUserLoginResult.orgId;
    var mActorId = currentActorId;
    if (mActorId != 7) {
        if (mOrgId == -2) {
            mActorId = 1;
        } else if(mOrgId) {
            mActorId = 3;
            localOrg = mOrgId;
        }
    }
    var id = "endRoad4Select";
    var url = "../rds_signalMachineManage/getSectionByStartRoad";
    var roadName = $("#startRoad4Select").find("option:selected").val();
    if (type == 1) {
        url = "../rds_signalMachineManage/getStartRoad";
        id = "startRoad4Select";
    }
    $.ajax({
        url: url,
        type: "POST",
        data: {
            "roadName": roadName,
            "actorId": mActorId,
            "orgId": localOrg
        },
        success: function (msg) {
            if (msg != null && typeof(msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var roadNames = msg.jsonData;
                    $("#" + id).empty();
                    if (roadNames.length != 0) {
                        // orgDataFlag = 0;
                        $("#" + id).append("<option value=''>起/止</option>");
                        for (var i = 0; i < roadNames.length; i++)
                            $("#" + id).append("<option value='" + roadNames[i] + "'>" +
                                roadNames[i] + "</option>");
                    } else
                        $("#" + id).append("<option>无</option>");
                    if (type == 1) {
                        $.getRoad(2);
                    }
                } else {
                    $.alert("获取监管单位数据失败", 2);
                }
            }
        }
    })
};

var bound_deviceType, bound_createTime, bound_deviceId, boundDt
$.boundAlarm = function (signalMachineId) {
    bound_deviceType = $("#DeviceType").val();
    if (!bound_deviceType)
        bound_deviceType = null;
    bound_createTime = "";
    bound_deviceId = "";
    boundDt = $("#boundDataTable").DataTable({
        ajax: {
            url: "../rds_alarmManage/getAlarmBySearch4DT",
            type: "POST",
            data: function (d) {
                d.search = "",
                    d.orgId = gUserLoginResult.orgId + ",-1";
                d.deviceType = bound_deviceType;
                d.createTime = bound_createTime;
                d.deviceId = bound_deviceId;
            }
        },
        columns: [{
            data: null,
            targets: 0
        }, {
            data: "orgName",
            render: function (data) {
                if (data)
                    return data;
                else
                    return "未设置";
            }
        }, {
            data: "createTime",
            render: function (data) {
                if (data)
                    return data.substr(0, 10);
                else
                    return "未知"
            }
        }, {
            data: "deviceId"
        }, {
//设备类型 0:标杆; 1:标牌; 2:; 3:信号机; 4:太阳能产品; 5:限高杆; 6:标线; 7:护栏; 8:监控箱; 9:井盖;
            data: "deviceType",
            render: function (data, type, row) {
                if (data) {
                    var result = "";
                    switch (data) {
                        case 2:
                            result = "已绑定信号灯";
                            break;
                        case 3:
                            result = "已绑定信号机";
                            break;
                        case 4:
                            result = "已绑定太阳能";
                            break;
                        case 5:
                            result = "已绑定限高杆";
                            break;
                        case 8:
                            result = "已绑定监控箱";
                            break;
                        case -1:
                            return "未绑定";
                            break;
                        default:
                            result = "已绑定其他设备";
                    }
                    return result + ": " + row.devicePathId;
                } else return "未绑定";
            }

        }, {
            data: "deviceId",
            render: function (data, type, row) {
                var disable1 = "", disable2 = "";
                if (row.deviceType == -1)
                    disable2 = "disabled";
                else
                    disable1 = "disabled";
                return "<button class='btn btn-primary btn-xs btn-flat' title='绑定' onclick='$.bindDevice(" + data + "," + signalMachineId + ")' " + disable1 + "><i class='fa fa-link'></i></button>&nbsp;" +
                    "<button class='btn btn-primary btn-xs btn-flat' title='解绑' onclick='$.unbindDevice(" + data + "," + signalMachineId + ")' " + disable2 + "><i class='fa fa-unlink'></i></button>";


            }
        }],
        dom: "<'row'<'col-md-2'><'#boundTool.col-md-10'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        //设备类型 0:标杆; 1:标牌; 2:; 3:; 4:; 5:; 6:标线; 7:护栏; 8:; 9:井盖;
        initComplete: function () {
            $("#boundTool").empty();
            var strToolBar = "<div class='input-group-sm' style='display:inline-block'>" +
                "<select class='form-control mysize'  style='width: 80px' id='DeviceType'>" +
                "<option value=''>信号机</option>" +
                "</select>&nbsp;" +
                "<input id='boundAlarmDatePicker'  type='text' class='form-control mysize' style='width: 100px;' placeholder='添加时间'>&nbsp;" +
                "<input type='text' class='form-control' style='width: 80px' id='bound_deviceId' placeholder='设备号'>" +
                "<button class='btn btn-primary btn-flat btn-sm' type='button' onclick='$.searchBoundDevice()'>" +
                "<i class='fa fa-search'></i></button></div></div>";
            $("#boundTool").append(strToolBar);
            $("#bound_deviceId").bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    $.searchBoundDevice();
                }
            });
            $('#boundAlarmDatePicker').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                todayBtn: 'linked',
                language: 'zh-CN'
            });
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        destroy: true,
        displayLength: 10,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    $("#boundModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
}

$.searchBoundDevice = function () {
    bound_deviceType = $("#DeviceType").val();
    if (!bound_deviceType)
        bound_deviceType = null;
    bound_createTime = $("#boundAlarmDatePicker").val();
    bound_deviceId = $("#bound_deviceId").val();
    boundDt.search("").draw();
}

$.bindDevice = function (deviceId, signalMachineId) {
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定要绑定该设备吗？ 可能会影响其他设备的绑定</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: "../rds_signalMachineManage/bindingDevice",
                    type: "POST",
                    data: {
                        deviceId: deviceId,
                        signalMachineId: signalMachineId,
                    },
                    success: function (msg) {
                        if (msg) {
                            if (msg.isSuccess && msg.jsonData >= 1) {
                                $.alert("绑定成功", 1);
                                boundDt.ajax.reload(null, false);
                                gMainDT.ajax.reload(null, false);
                            }
                            else
                                $.alert("绑定失败", 2);
                        } else
                            $.alert("系统错误", 2);
                    }
                })
            }
        }

    })
}

$.unbindDevice = function (deviceId, signalMachineId) {
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定要解除该设备的绑定吗？ 可能会影响其他设备的绑定</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: '../rds_signalMachineManage/unbindingDevice',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        deviceId: deviceId,
                        signalMachineId: signalMachineId,
                    },
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                $.alert("解绑成功", 1);
                                boundDt.ajax.reload(null, false);
                                gMainDT.ajax.reload(null, false);
                            } else {
                                $.alert("操作失败", 2);
                            }
                        } else {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    },
                    error: function () {
                        $.alert('系统错误，请联系管理员', 2);
                    }
                });
            }
        }
    });
}
/********************DT功能组建*************************************/
$.fn.searchDT = function () {
    startRoad4Select = $("#startRoad4Select").val();
    endRoad4Select = $("#endRoad4Select").val();
    alarmBinding = $("#alarm4Select").val();
    localOrgId = $("#orgId4Select").val();
    if (localActorId != 7) {
        if (localOrgId == -2) {
            localActorId = 1;
        } else {
            localActorId = 3;
        }
    }
    if(!localOrgId)
    {
        localOrgId = gUserLoginResult.orgId;
    }
    gMainDT.search($("#searchText").val()).draw();
};


$.checkChange = function () {
    var isChecked = $("#batchCheck").prop('checked');
    $("input:checkbox[id^='checkbox']").prop("checked", isChecked);
};

$.showInfo = function (jsonData) {
    $(".no_act").show();
    $("#defaultFooter").hide();
    $("#specialFooter").show();
    $("#myBtn").attr("onclick", "$.showMap(" + jsonData.signalMachineLongitude + "," + jsonData.signalMachineLatitude + ")");
    $.showUpdateSignalMachine(jsonData, 3);
};

$.beDefault = function () {
    $("#myBtn").attr("onclick", "");
    $(".no_act").hide();
    $("#defaultFooter").show();
    $("#specialFooter").hide();
};

$.showMap = function (x, y) {
    X = x;
    Y = y;
    $("#modalMapRoad").hide();
    var url = "management/poleMap.html";
    url += "?x=" + x + "&y=" + y + "&z=1";//通过这种方式传参数
    $("#myMap").attr("src", url);
    $("#modal-map").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
};

$.showHistory = function (signalMachineId) {
    historyDt = $("#historyDataTable").DataTable({
        ajax: {
            url: "../rds_roadSignManageController/getHistory4DT",
            type: "POST",
            data: function (d) {
                d.search = $('#historyDataTable').DataTable().search(this.value);
                d.equipmentId = signalMachineId;
                d.equipmentType = 3;
            }
        },
        columns: [{
            data: null,
            targets: 0
        }, {
            data: "eventType"
        }, {
            data: "operatingTime"
        }, {
            data: "operatingPerson"
        }],
        dom: "<'row'<'col-md-6'><'#historyTool.col-md-6'>r>t<'row'<'col-md-5'i><'col-md-7'p>>",
        initComplete: function () {
            $("#historyTool").empty();
            var strToolBar = "<div class='input-group input-group-sm'>" +
                "<input type='text' class='form-control' id='datePicker' placeholder='操作时间'>" +
                "<span class='input-group-btn'>" +
                "<button class='btn btn-primary btn-flat' type='button' " +
                "onclick='$(this).searchInfoInHistoryDt()'><i class='fa fa-search'></i>" +
                "</button></span></div>";
            $("#historyTool").append(strToolBar);
            $("#datePicker").bind('keydown', function (event) {
                if (event.keyCode == "13") {
                    $(this).searchInfoInHistoryDt();
                }
            });
            $('#datePicker').datepicker({
                format: 'yyyy-mm-dd',
                autoclose: true,
                todayBtn: 'linked',
                language: 'zh-CN'
            });
        },
        processing: true,
        serverSide: true,
        ordering: false,
        select: false,
        autoFill: true,
        destroy: true,
        displayLength: 10,
        lengthMenu: [[5, 10, 15, 20, 50, 100, 150, -1], [5, 10, 15, 20, 50, 100, 150, "All"]],
        language: {
            url: "zh_cn.json"
        },
        fnDrawCallback: function () {// 序号自增回调函数
            var api = this.api();
            var startIndex = api.context[0]._iDisplayStart;
            api.column(0).nodes().each(function (cell, i) {
                cell.innerHTML = startIndex + i + 1;
            });
        }
    });

    $("#historyModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$.showQrcode = function (jsonData) {
    $("#qrcode").empty();
    var qrcode = new QRCode(document.getElementById("qrcode"), {
        width: 200,
        height: 200
    });
    qrcode.makeCode("orgId:" + jsonData.signalMachineOrgId + ",signalMachineId:" + jsonData.signalMachineId);
    $("#qrcodeModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

/********************DT功能组建end**********************************/

/********************添加模态框组件*********************************/

$('#signalMachineInstallTime').datepicker({
    format: 'yyyy-mm-dd',
    autoclose: true,
    todayBtn: 'linked',
    language: 'zh-CN'
});

$.getMainOrgNameAndId = function (orgId) {
    $.ajax({
        url: "../rds_org/getMainOrgNameAndId",
        type: 'post',
        async: false,
        dataType: 'json',
        data: {
            'orgId': orgId
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var orgData = msg.jsonData;
                    $("#signalMachineMainOrgId").empty();
                    if (orgData.length != 0) {
                        orgDataFlag = 0;
                        for (var i = 0; i < orgData.length; i++)
                            $("#signalMachineMainOrgId").append("<option value='" + orgData[i].orgId + "'>" +
                                orgData[i].orgName + "</option>");
                    } else {
                        orgDataFlag = 1;
                        $("#signalMachineMainOrgId").append("<option value='" + gUserLoginResult.orgId + "'>" +
                            gUserLoginResult.orgName + "</option>");
                    }
                } else {
                    $.alert("获取监管单位数据失败", 2);
                }
            } else {
                $.alert('系统错误', 2);
            }
        },
        error: function () {
            $.alert("系统错误", 2);
        }
    });
};


/*********************图片上传********************************/
$.openUpPic = function () {
    $("#upPictureModal").modal({
        backdrop: 'static',
        keyboard: true,
        show: true
    });
};

$.closeUpPhModal = function () {
    $("#upPictureModal").modal("hide");
    $("#ossfile").empty();
    clearOssData();
};

$.doneUpPhoto = function () {
    var fileInfo = getOssFileInfo();
    var fileUrl = fileInfo[0].fileUrl;
    $("#signalMachinePhotoImg").attr("src", fileUrl);
    $("#signalMachinePhoto").val(fileUrl);
    $.closeUpPhModal();
};

function judgeFileType(suffix) {
    //图片文件
    if (!(suffix == ".jpg" || suffix == ".JPG" || suffix == ".png" || suffix == ".PNG" ||
        suffix == ".jpeg" || suffix == ".JPEG" || suffix == ".gif" || suffix == ".GIF" ||
        suffix == ".bmp" || suffix == ".BMP")) {
        alert("请选择图片文件！");
        return false;
    }
}

/*********************图片上传end*****************************/

/*********************地图***********************************/
$("#myBtn").click(function () {
    $("#modalMapRoad").show();
    $("#startRoad").val($("#signalMachineStartRoad").val());
    $("#endRoad").val($("#signalMachineEndRoad").val());
    var url = "management/roadPoleMap.html";
    var coo = $("#coordinate").val(),
        coordinate,
        type = 1,
        x, y;
    if (coo != "") {
        coordinate = $("#coordinate").val().split(",");
        x = coordinate[0];
        y = coordinate[1];
    } else {
        x = $("#city").find("option:selected").text();
        y = $("#area").find("option:selected").text();
        type = 0;
    }
    url += "?x=" + x + "&y=" + y + "&z=" + type + "";//通过这种方式传参数
    signalMachineArea = $("#area").val();
    $("#myMap").attr("src", url);
    $("#modal-map").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    })
});

$("#subBtn").click(function () {
    $("#signalMachineStartRoad").val($("#startRoad").val());
    $("#signalMachineEndRoad").val($("#endRoad").val());
    //  $("#signalMachineRoadName").val(sessionStorage.getItem("roadName"));
    $("#coordinate").val(sessionStorage.getItem("x") + "," + sessionStorage.getItem("y"));
    $('#modal-map').modal("hide");
});

/*********************地图end********************************/


/*********************地域选择********************************/

$.getRegion = function (id, pid) {
    $.ajax({
        url: "../rds_roadSignManageController/getRegion4Select",
        type: 'post',
        async: false,
        dataType: 'json',
        data: {
            'pid': pid
        },
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    var provinceData = msg.jsonData;
                    $("#" + id).empty();
                    if (provinceData.length != 0) {
                        provinceDataFlag = 0;
                        for (var i = 0; i < provinceData.length; i++)
                            $("#" + id).append("<option value='" + provinceData[i].regionId + "'>" +
                                provinceData[i].regionName + "</option>");
                    }
                    else {
                        provinceDataFlag = 1;
                        $("#" + id).append("<option value='" + gUserLoginResult.regionId + "'>" +
                            gUserLoginResult.regionName + "</option>");
                    }
                } else {
                    $.alert("获取地区列表失败", 2);
                }
            } else {
                $.alert('系统错误', 2);
            }
        },
        error: function () {
            $.alert("系统错误", 2);
        }
    });
};

$("#province").change(function () {
    signalMachineProvince = $("#province").val();
    $.getRegion("city", $("#province").val());
    $("#city").val(parseInt($("#province").val()) + 100);
    signalMachineCity = $("#city").val();
    $.getRegion("area", $("#city").val());
    $("#area").val(parseInt($("#city").val()) + 1);
    signalMachineArea = $("#area").val();
});

$("#city").change(function () {
    signalMachineCity = $("#city").val();
    $.getRegion("area", $("#city").val());
    $("#area").val(parseInt($("#city").val()) + 1);
    signalMachineArea = $("#area").val();
});

$("#area").change(function () {
    signalMachineArea = $("#area").val();
});

/*********************地域选择end*****************************/

/*********************form表单 添加编辑***********************/

$.showAddSignalMachine = function () {
    signalMachineFlag = 0;
    $.getRegion("province", 0);
    if (signalMachineProvince == 0)
        $("#province").val(330000);
    else
        $("#province").val(signalMachineProvince);
    $.getRegion("city", $("#province").val());
    if (signalMachineCity == 0)
        $("#city").val(330200);
    else
        $("#city").val(signalMachineCity);
    $.getRegion("area", $("#city").val());
    if (signalMachineArea == 0)
        $("#area").val(330211);
    else
        $("#area").val(signalMachineArea);


    $("#signalMachineInstallTime").val(date);
    $("#signalMachineOrgName").val(gUserLoginResult.orgName);
    $("#signalMachinePhotoImg").attr("src", "../images/default_photo.png");
    $("#signalMachinePeriod").val(1);
    $("#signalMachineServiceLife").val(1);
    $.getMainOrgNameAndId(gUserLoginResult.orgId);
    $("#signalMachineType").val(0);
    $("#signalMachineIsAlarm").val(1);
    $("#signalMachineCreatorName").val(gUserLoginResult.userName);
    $("#signalMachineCreatorId").val(gUserLoginResult.userId);
    $("#signalMachineOrgId").val(gUserLoginResult.orgId);
    $("#signalMachinePhoto").val("../images/default_photo.png");

    $("#signalMachineLabel").text("添加信号机信息");
    $("#signalMachineModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$('#signalMachineForm').bootstrapValidator({
    feedbackIcons: {
        valid: 'glyphicon glyphicon-ok',
        invalid: 'glyphicon glyphicon-remove',
        validating: 'glyphicon glyphicon-refresh'
    },
    fields: {
        projectNumber: {
            validators: {
                stringLength: {max: 20, message: '项目编号长度不超过20'}
            }
        },
        coordinate: {
            validators: {
                notEmpty: {message: '坐标不能为空'},
                stringLength: {max: 40, message: '坐标长度不超过40'}
            }
        },
        signalMachineRoadName: {
            validators: {
                notEmpty: {message: '路名不能为空'},
                stringLength: {max: 20, message: '路名长度不超过20'}
            }
        },
        signalMachineStartRoad: {
            validators: {
                notEmpty: {message: '起始路口不能为空'},
                stringLength: {max: 20, message: '路名长度不超过20'}
            }
        },
        signalMachineEndRoad: {
            validators: {
                notEmpty: {message: '结束路口不能为空'},
                stringLength: {max: 20, message: '路名长度不超过20'}
            }
        },
        signalMachineBrand: {
            validators: {
                stringLength: {max: 20, message: '品牌长度不超过20'}
            }
        },
        signalMachineInstallOrg: {
            validators: {
                stringLength: {max: 50, message: '安装公司长度不超过50'}
            }
        },
        signalMachineInstallTime: {
            validators: {
                stringLength: {max: 50, message: '安装日期长度不超过50'}
            }
        },
        signalMachineRemark: {
            validators: {
                stringLength: {max: 200, message: '说明备注长度不超过200'}
            }
        }
    }
}).on('success.form.bv', function (e) {
    e.preventDefault();
    var coordinate = $("#coordinate").val().split(",");
    $("#signalMachineProvince").val($("#province").find("option:selected").text());
    $("#signalMachineCity").val($("#city").find("option:selected").text());
    $("#signalMachineArea").val($("#area").find("option:selected").text());
    $("#signalMachineLongitude").val(coordinate[0]);
    $("#signalMachineLatitude").val(coordinate[1]);
    $("#signalMachineRegionId").val($("#area").val());

    var $form = $(e.target);
    var url;
    var formData = $form.serialize();
    if (signalMachineFlag == 0)
        url = "../rds_signalMachineManage/addSignalMachine";
    else
        url = "../rds_signalMachineManage/updateSignalMachine";
    $.ajax({
        url: url,
        type: 'post',
        data: formData,
        dataType: 'json',
        success: function (msg) {
            if (msg != null && typeof (msg) != "undefined") {
                if (msg.isSuccess == true) {
                    $.alert("数据操作成功", 1);
                    gMainDT.ajax.reload(null, false);
                    gMainDT.ajax.reload(null, false);
                    var roadNameA = $("#startRoad4Select").val(),
                        roadNameB = $("#endRoad4Select").val();
                    $.getRoad(1);
                    setTimeout(function () {
                        $("#startRoad4Select").val(roadNameA);
                        $("#endRoad4Select").val(roadNameB);
                        console.log(roadNameA + " " + roadNameB);
                    }, 200);
                } else {
                    $.alert("数据操作失败", 2);
                }
            } else {
                $.alert('系统错误，请联系管理员', 2);
            }
        },
        error: function () {
            $.alert('系统错误，请联系管理员', 2);
        }
    });
    $.clearModal($("#signalMachineForm"), $("#signalMachineModal"));
});

$.showUpdateSignalMachine = function (jsonData) {
    map_type = (arguments[1]) ? arguments[1] : 1;
    $("#signalMachineLabel").text(map_type == 1 ? "编辑信息" : "信息展示");//展示or编辑


    signalMachineFlag = 1;
    $("#projectNumber").val(jsonData.projectNumber);
    $.getRegion("province", 0);
    $("#province").val(jsonData.signalMachineRegionId.toString().substring(0, 2) + "0000");
    $.getRegion("city", $("#province").val());
    $("#city").val(jsonData.signalMachineRegionId.toString().substring(0, 4) + "00");
    $.getRegion("area", $("#city").val());
    $("#area").val(jsonData.signalMachineRegionId);

    $("#coordinate").val(jsonData.signalMachineLongitude + "," + jsonData.signalMachineLatitude);
    $("#signalMachineStartRoad").val(jsonData.signalMachineStartRoad);
    $("#signalMachineEndRoad").val(jsonData.signalMachineEndRoad);
    $("#signalMachineBrand").val(jsonData.signalMachineBrand);
    $("#signalMachineInstallOrg").val(jsonData.signalMachineInstallOrg);
    $("#signalMachineInstallTime").val(jsonData.signalMachineInstallTime);
    $("#signalMachineRemark").val(jsonData.signalMachineRemark);
    $("#signalMachineOrgName").val(jsonData.signalMachineOrgName);
    $("#signalMachinePhotoImg").attr("src", jsonData.signalMachinePhoto);
    $("#signalMachinePeriod").val(jsonData.signalMachinePeriod);
    $("#signalMachineServiceLife").val(jsonData.signalMachineServiceLife);
    $.getMainOrgNameAndId(gUserLoginResult.orgId);
    orgDataFlag == 0 ?
        $("#signalMachineMainOrgId").val(jsonData.signalMachineMainOrgId) :
        $("#signalMachineMainOrgId").val(gUserLoginResult.orgId);
    $("#signalMachineType").val(jsonData.signalMachineType);
    $("#signalMachineNumber").val(jsonData.signalMachineNumber);
    $("#signalMachineId").val(jsonData.signalMachineId);
    $("#signalMachineIsAlarm").val(jsonData.signalMachineIsAlarm);
    $("#signalMachineCreatorName").val(jsonData.signalMachineCreatorName);
    $("#signalMachineCreatorId").val(jsonData.signalMachineCreatorId);
    $("#signalMachineModifierId").val(gUserLoginResult.userId);
    $("#signalMachineOrgId").val(jsonData.signalMachineOrgId);
    $("#signalMachinePhoto").val(jsonData.signalMachinePhoto);

    $("#signalMachineModal").modal({
        backdrop: 'static',
        keyboard: false,
        show: true
    });
};

$.showDeleteSignalMachine = function (signalMachineId) {
    var count = 1;
    if (signalMachineId == 0) {
        count = $("input:checkbox[id^='checkbox']:checked").length;
        if (count == 0) {
            $.alert("请选择要删除的数据", 2);
            return;
        } else {
            signalMachineId = "";
            $("input:checkbox[id^='checkbox']:checked").each(function () {
                signalMachineId += $(this).val() + ",";
            });
            signalMachineId = signalMachineId.substring(0, signalMachineId.length - 1);
        }
    }
    bootbox.confirm({
        buttons: {
            confirm: {
                label: '<i class="fa fa-check"></i> 确定',
                className: 'btn btn-primary btn-flat'
            },
            cancel: {
                label: '<i class="fa fa-close"></i> 取消',
                className: 'btn btn-warning btn-flat pull-left'
            }
        },
        message: '<i class="fa fa-question-circle-o"></i> <b class="customer-title">确定删除该' + count + '条数据吗?</b>',
        callback: function (result) {
            if (result) {
                $.ajax({
                    url: '../rds_signalMachineManage/deleteSignalMachine',
                    type: 'post',
                    dataType: 'json',
                    data: {
                        "signalMachineIds": signalMachineId
                    },
                    success: function (msg) {
                        if (msg != null && typeof (msg) != "undefined") {
                            if (msg.isSuccess == true) {
                                $.alert("数据删除成功", 1);
                                gMainDT.ajax.reload(null, false);
                                gMainDT.ajax.reload(null, false);
                                var roadNameA = $("#startRoad4Select").val(),
                                    roadNameB = $("#endRoad4Select").val();
                                $.getRoad(1);
                                setTimeout(function () {
                                    $("#startRoad4Select").val(roadNameA);
                                    $("#endRoad4Select").val(roadNameB);
                                    console.log(roadNameA + " " + roadNameB);
                                }, 200);
                            } else {
                                $.alert("数据删除失败", 2);
                            }
                        } else {
                            $.alert('系统错误，请联系管理员', 2);
                        }
                    },
                    error: function () {
                        $.alert('系统错误，请联系管理员', 2);
                    }
                });
            }
        }
    });
};

